import BreadcrumbDept from '@/components/BreadcrumbDept';
import PermissionControl from '@/components/PermissionControl';
import TableHint from '@/components/TableHint/Index';
import {
  doCreateGoods,
  downGoodsList,
  getBrandListByPage,
  getCategoryListByPage,
  getGoodsList,
  updateGoods,
  updateGoodsStauts
} from '@/services/stock-goods/api';
import { OptType } from '@/utils/constants';
import { MsgType, showMsg } from '@/utils/utils';
import { PlusOutlined } from '@ant-design/icons';
import { ProFormFieldSet } from '@ant-design/pro-form';
import { PageContainer } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import type { FormInstance } from 'antd';
import { Button, Checkbox, InputNumber, Popconfirm, Switch } from 'antd';
import { useEffect, useRef, useState } from 'react';
import { useModel } from 'umi';
import GoodsDetail from './Detail';
import OptForm from './OptForm';
import './style.less';
import { subGoodsList } from '@/services/stock-goods/subApi';

type SearchParams = {
  class_id?: string;
  brand_id?: string;
  goods_id?: string;
  goods_name?: string;
  goods_status?: string;
  key_words?: string;
  max_inventory?: number;
  min_inventory?: number;
  not_brand_id?: string;
  not_class_id?: string;
  start_price?: number;
  end_price?: number;
  flag?: string;
  inventory_range?: string[];
  price_range?: string[];
}

const GoodsList = () => {

  const ref = useRef<FormInstance>();
  const actionRef = useRef<ActionType>();
  const [loading, setLoading] = useState<boolean>(false);
  const [searchParams, setSearchParams] = useState({});

  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [detailVisible, setDetailVisible] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<STOCKGOODSAPI.GoodsItem>({});
  const [optType, setOptType] = useState<string>(OptType.ADD);
  // 仅查看库存告警商品
  const [checked, setChecked] = useState<boolean>(false);
  const [warningCount, setWarningCount] = useState<number>(0);
  // 品类列表
  const [classList, setClassList] = useState<COMMON.SelectOption[]>([]);
  // 品牌列表
  const [brandList, setBrandList] = useState<COMMON.SelectOption[]>([]);
  // 是否可下载
  const [downloadFlag, setDownloadFlag] = useState<boolean>(false);
  // 当前选中的行编号，用于定位颜色
  const [clickRow, setClickRow] = useState<string>();

  const { initialState } = useModel('@@initialState');
  const dept_level = initialState?.currentUser?.dept_level;

  const columns: ProColumns<STOCKGOODSAPI.GoodsItem>[] = [
    {
      title: '商品分类',
      dataIndex: 'class_id',
      valueType: 'select',
      hideInTable: true,
      fieldProps: {
        options: classList,
        showSearch: true,
        filterOption: true
      }
    },
    {
      title: '商品分类',
      dataIndex: 'class_name',
      search: false
    },
    {
      title: '商品名称',
      dataIndex: 'goods_name',
      hideInTable: true,
      fieldProps: {
        placeholder: '商品名称或检索码'
      }
    },
    {
      title: '商品品牌',
      dataIndex: 'brand_id',
      hideInTable: true,
      valueType: 'select',
      fieldProps: {
        options: brandList,
        showSearch: true,
        filterOption: true
      }
    },
    {
      title: '品牌',
      key: 'brand_name',
      dataIndex: 'brand_name',
      search: false
    },
    {
      title: '名称',
      dataIndex: 'goods_name',
      search: false
    },
    {
      title: '规格数',
      dataIndex: 'specs_num',
      search: false,
      align: 'right',
      valueType: 'digit',
    },
    {
      title: '库存',
      dataIndex: 'total_inventry',
      search: false,
      align: 'right',
      valueType: 'digit',
    },
    {
      title: '待出库',
      dataIndex: 'wait_inventory',
      search: false,
      align: 'right',
      valueType: 'digit',
    },
    {
      title: '销量',
      dataIndex: 'salves_volume',
      search: false,
      align: 'right',
      valueType: 'digit',
    },
    {
      title: '上架状态',
      dataIndex: 'goods_status',
      valueType: 'select',
      width: 60,
      align: 'center',
      valueEnum: {
        O: '已上架',
        D: '已下架'
      },
      render: (_, record) => (
        dept_level === '2' ? (record.goods_status === 'O' ? '已上架' : '已下架') :
          <PermissionControl action_id="200200002">
            <Popconfirm
              title={record.goods_status === 'O' ? '您即将下架此商品，是否确认？' : '您即将上架此商品，是否确认？'}
              onConfirm={() => { handleGoodsStatus(record) }}
            >
              <Switch checked={record.goods_status === 'O'} />
            </Popconfirm>
          </PermissionControl>
      )
    },
    {
      title: '零售价格',
      dataIndex: 'price_range',
      hideInTable: true,
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        if (type === 'form') {
          return null;
        }
        return (
          <ProFormFieldSet>
            <InputNumber precision={2} style={{ width: '100%' }} placeholder="最低价" />
            <span style={{ padding: '0 5px' }}>-</span>
            <InputNumber precision={2} style={{ width: '100%' }} placeholder="最高价" />
          </ProFormFieldSet>
        );
      }
    },
    {
      title: '库存',
      dataIndex: 'inventory_range',
      hideInTable: true,
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        if (type === 'form') {
          return null;
        }
        return (
          <ProFormFieldSet>
            <InputNumber precision={2} style={{ width: '100%' }} placeholder="最小值" />
            <span style={{ padding: '0 5px' }}>-</span>
            <InputNumber precision={2} style={{ width: '100%' }} placeholder="最大值" />
          </ProFormFieldSet>
        );
      }
    },
    {
      title: '1',
      dataIndex: 'flag',
      hideInTable: true,
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        if (type === 'form') {
          return null;
        }
        return (
          <Checkbox checked={checked} onChange={e => setChecked(e.target.checked)}>
            只查看库存告警商品
          </Checkbox>
        )
      }
    },
    {
      title: '操作',
      valueType: 'option',
      align: 'center',
      render: (_, record: STOCKGOODSAPI.GoodsItem) => [
        <PermissionControl key="view" action_id="200200003">
          <a onClick={() => {
            setDetailVisible(true);
            setCurrentRow(record);
          }}>查看</a>
        </PermissionControl>,
        dept_level !== '2' && <PermissionControl key="edit" action_id="200200004">
          <a onClick={() => {
            handleModalVisible(true);
            setCurrentRow(record);
            setOptType(OptType.EDIT);
          }}>编辑</a>
        </PermissionControl>
      ]
    }
  ];

  // 点击查看
  const onView = () => {
    setChecked(true);
    if (ref.current) {
      ref.current.submit();
    }
  }

  /**
   * 添加商品
   * @param fields
   */
  const handleAdd = async (fields: any) => {
    try {
      if (optType === OptType.ADD) {
        await doCreateGoods({ ...fields });
      } else {
        await updateGoods({ ...fields });
      }
      init();
      showMsg('已保存', MsgType.SUCCESS);
      actionRef.current?.reload();
      return true
    } catch (error: any) {
      showMsg(error?.data?.errmsg);
      return false
    }
  }

  /**
   * 上下架商品
   * @param record
   */
  const handleGoodsStatus = async (record: STOCKGOODSAPI.GoodsItem) => {
    if (!record) {
      return;
    }
    try {
      const { goods_id, goods_status } = record;
      await updateGoodsStauts({ goods_id, goods_status: goods_status === 'O' ? 'D' : 'O' });
      showMsg(`商品已${record.goods_status === 'O' ? '下架' : '上架'}`, MsgType.SUCCESS);
      actionRef.current?.reload();
    } catch (error: any) {
      showMsg(error?.data?.errmsg);
    }
  }

  const init = () => {
    getCategoryListByPage({ current: 1, pageSize: 10000 }).then((res: STOCKGOODSAPI.CategoryItemList) => {
      const list = res.record_list?.map(({ class_id, class_py, class_name }: any) => (
        { value: `${class_id}|${class_py}`, label: class_name }
      ));
      setClassList(list || []);
    });
    getBrandListByPage({ current: 1, pageSize: 10000 }).then((res: STOCKGOODSAPI.BrandItemList) => {
      const list = res.record_list?.map(({ brand_id, brand_py, brand_name }: any) => (
        { value: `${brand_id}|${brand_py}`, label: brand_name }
      ));
      setBrandList(list || []);
    });
  }

  const download = async () => {
    setLoading(true);
    await downGoodsList(searchParams).then(res => {
      setLoading(false);
      window.open(`/api/report/${res.file_token}/down`);
    }).catch(res => {
      setLoading(false);
    });
  }

  useEffect(() => {
    init()
  }, []);

  return (
    <PageContainer extra={<BreadcrumbDept />} breadcrumb={{}} className="goods-container">
      <ProTable<STOCKGOODSAPI.GoodsItem, SearchParams & COMMON.PageParams>
        actionRef={actionRef}
        rowKey="goods_id"
        bordered
        rowClassName={record => {
          let cls = record.goods_id === clickRow ? 'tableRowClick' : ''
          if (record.total_inventory && record.wait_inventory && record.wait_inventory) {
            cls += record.total_inventory - record.wait_inventory <= record.wait_inventory ? 'update-bg' : ''
          }
          return cls.trim();
        }}
        formRef={ref}
        search={{
          span: 6,
          collapsed: false,
          collapseRender: false,
          optionRender: (searchConfig, formProps, dom) => ([
            <PermissionControl key="search" action_id="200200000">
              <Button onClick={() => formProps.form?.submit()} type="primary">查询</Button>
            </PermissionControl>,
            <PermissionControl key="export" action_id="200200006">
              <Button key="export" type="primary" loading={loading} disabled={!downloadFlag} onClick={download}>导出报表</Button>
            </PermissionControl>
          ])
        }}
        request={async (params: COMMON.PageParams & SearchParams) => {
          if (params.inventory_range) {
            params.min_inventory = Number(params.inventory_range[0]);
            params.max_inventory = Number(params.inventory_range[2]);
            delete params.inventory_range;
          }

          if (params.price_range) {
            params.start_price = Number(params.price_range[0]);
            params.end_price = Number(params.price_range[2]);
            delete params.price_range;
          }

          if (params.class_id) {
            params.class_id = params.class_id.split('|')[0];
          }
          if (params.brand_id) {
            params.brand_id = params.brand_id.split('|')[0];
          }

          if (checked) {
            params.flag = '1';
          } else {
            params.flag = '0';
          }

          const { start_price, end_price, min_inventory, max_inventory } = params;
          // 比较大小
          if (start_price && !isNaN(start_price) && end_price && !isNaN(end_price)) {
            if (start_price > end_price) {
              showMsg('零售价格最大值不能小于最小值', MsgType.INFO);
              return { success: false, data: [] };
            }
          }
          if (min_inventory && !isNaN(min_inventory) && max_inventory && !isNaN(max_inventory)) {
            if (min_inventory > max_inventory) {
              showMsg('库存最大值不能小于最小值', MsgType.INFO);
              return { success: false, data: [] };
            }
          }
          setSearchParams(params);
          try {
            let data;
            if (dept_level === '2') {
              data = await subGoodsList(params);
            } else {
              data = await getGoodsList(params);
            }
            setWarningCount(data.warn_num);
            setDownloadFlag((data.record_list?.length ?? 0) > 0)
            return {
              success: true,
              data: data.record_list,
              total: data.sum_record_num
            };
          } catch (error: any) {
            setDownloadFlag(false);
            showMsg(error?.data?.errmsg);
            return {
              success: false,
              data: []
            };
          }
        }}
        options={false}
        columns={columns}
        className='mytable mytable1'
        toolBarRender={() => [
          <>
            {
              dept_level !== '2' &&
              <PermissionControl action_id="200200001">
                <Button icon={<PlusOutlined />} type="primary" onClick={() => {
                  setCurrentRow({});
                  handleModalVisible(true);
                  setOptType(OptType.ADD);
                }}>新增</Button>
              </PermissionControl>
            }
            {
              warningCount > 0 &&
              <TableHint
                text={
                  <div>
                    有 <span style={{ color: '#F2232C', fontWeight: 'bold' }}>{warningCount}</span>
                    个商品库存告警，请及时补货。（告警条件：库存 - 待出库量 ≤ 库存告警量）
                  </div>
                }
                onAction={() => onView()}
                showAction
              />
            }
          </>
        ]}
        pagination={{ showQuickJumper: true }}
        onRow={record => ({ onClick: () => setClickRow(record.goods_id) })}
      />
      {
        detailVisible && <GoodsDetail
          handleModalVisible={setDetailVisible}
          record={currentRow}
        />
      }
      {
        createModalVisible && <OptForm
          handleAdd={handleAdd}
          handleModalVisible={handleModalVisible}
          record={currentRow}
          optType={optType}
        />
      }
    </PageContainer>
  );
};
export default GoodsList;
